<script setup lang="ts">
import type { Ref } from 'vue'
import type { CodeMateModel } from '@/apis/code/codeMateApi'
import { storeToRefs } from 'pinia'
import { computed, inject, onMounted, ref, watch } from 'vue'
import { useDictStore } from '@/stores/dictStore'

const type = defineModel<string>('type')
const modelId = defineModel<number>('modelId')
const isList = defineModel<boolean>('isList')

const models = inject<Ref<CodeMateModel[]>>('models')
const typeValue = ref<string>()

const dictStore = useDictStore()
const { dictMap } = storeToRefs(dictStore)

onMounted(async () => {
  await dictStore.loadDict('ENUM_CODE_MATE_FIELD_TYPE')
  typeValue.value = modelId.value === undefined ? type.value : `OBJECT_${modelId.value}`
})

watch(() => typeValue.value, () => {
  if (typeValue.value?.startsWith('OBJECT_')) {
    type.value = 'OBJECT'
    modelId.value = Number.parseInt(typeValue.value.substring(7))
  }
  else {
    type.value = typeValue.value
    modelId.value = undefined
  }
})

const showTitle = computed(() => {
  if (modelId.value !== undefined) {
    const model = models?.value?.find(t => t.id === modelId.value)
    if (model !== undefined) {
      return {
        title: isList.value ? `${model.remark}列表` : model.remark,
        name: isList.value ? `List<${model.name}>` : model.name,
      }
    }
  }
  else {
    const filedType = dictMap.value.ENUM_CODE_MATE_FIELD_TYPE?.find(t => t.dictCode === type.value)
    if (filedType) {
      return {
        title: isList.value ? `${filedType.dictName}列表` : filedType.dictName,
        name: isList.value ? `List<${filedType.dictCode}>` : `${filedType.dictCode}`,
      }
    }
  }
  return undefined
})
</script>

<template>
  <el-select v-model="typeValue">
    <template #header>
      <el-checkbox v-model="isList">
        列表
      </el-checkbox>
    </template>
    <template v-if="showTitle !== undefined" #label>
      <div class="flex items-center gap-2">
        <span>{{ showTitle.title }} </span>
        <span class="text-xs text-secondary">{{ showTitle.name }}</span>
      </div>
    </template>
    <el-option-group label="基础">
      <template v-for="t in dictMap.ENUM_CODE_MATE_FIELD_TYPE" :key="t.dictCode">
        <el-option v-if="t.dictCode !== 'OBJECT'" :label="t.dictName" :value="t.dictCode!">
          <div class="flex items-center justify-between">
            <span>{{ t.dictName }}</span>
            <span class="text-xs text-secondary">{{ t.dictCode }}</span>
          </div>
        </el-option>
      </template>
    </el-option-group>
    <el-option-group v-if="models !== undefined && models.length > 0" label="模型">
      <el-option v-for="m in models" :key="m.id" :label="m.remark" :value="`OBJECT_${m.id}`">
        <div class="flex items-center justify-between">
          <span>{{ m.remark }}</span>
          <span class="text-xs text-secondary">{{ m.name }}</span>
        </div>
      </el-option>
    </el-option-group>
  </el-select>
</template>
